package com.pro.framework.api;

import java.util.function.Function;

public class NewtonMethodSolver {
    private static final double EPSILON = 1e-6; // 允许误差

    public static double solve(Function<Double, Double> f, Function<Double, Double> df, double x0) {
        double x = x0;
        int maxIterations = 1000; // 最大迭代次数
        int iter = 0;
        while (Math.abs(f.apply(x)) > EPSILON && iter < maxIterations) {
            double fx = f.apply(x);
            double dfx = df.apply(x);
            if (Math.abs(dfx) < EPSILON) { // 避免除零错误
                throw new ArithmeticException("导数接近 0，牛顿法可能无法收敛");
            }
            x = x - fx / dfx;
            iter++;
        }
        return x;
    }

    public static void main(String[] args) {
        // f(x) = x^3 - 2x - 5
        Function<Double, Double> f = x -> Math.pow(x, 3) - 2 * x - 5;
        // f'(x) = 3x^2 - 2
        Function<Double, Double> df = x -> 3 * Math.pow(x, 2) - 2;

        double root = solve(f, df, 2); // 选取初始值 2
        System.out.println("方程的根为: " + root);
    }
}
